package com.hotel.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.commontools.data.DataTool;
import com.commontools.validate.ValidateTool;
import com.hotel.util.RedisSessionUtil;
import com.hotel.util.ResultCode;
import com.hotel.util.StaticValue;

/**
 * 
 * @ClassName: HttpRequestLoginInterceptor 
 * @Description: 拦截接口 拦截用户是否已经登陆
 * @author: liupengyan
 * @date: 2016年3月18日 上午10:38:27
 */
public class HttpRequestLoginInterceptor implements HandlerInterceptor {
	@Resource
	private RedisSessionUtil redisSessionUtil;
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
		String sessionId = request.getHeader("session_id");

		if (sessionId == null) {

			response.getWriter().write(DataTool.constructResponse(
							ResultCode.NOT_LOGIN, "未登陆", null));
			return false;
		}
		try {

			String session_user_id = (String) redisSessionUtil
					.getSession("sessionId_" + sessionId);

			if (ValidateTool.isEmptyStr(session_user_id)) {

				response.getWriter().write(DataTool.constructResponse(
								ResultCode.NOT_LOGIN, "未登陆", null));
				return false;
			} else {
				redisSessionUtil.setSession("sessionId_" + sessionId,
						session_user_id, StaticValue.USER_SESSION_EXPIRE_TIME);
				return true;
			}

		} catch (Exception e) {
			e.printStackTrace();
			response.getWriter().write(DataTool.constructResponse(
							ResultCode.SYSTEM_ERROR, "系统错误", null));
			return false;
		}
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
